package com.kb.erp.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import com.kb.erp.dto.BusinessQueryParam;
import com.kb.erp.entity.pcbout.*;
import com.kb.erp.entity.quote.BaseResult;
import com.kb.erp.service.MaterialService;
import com.kb.erp.service.PCBOutService;
import com.kb.erp.service.impl.DYYServiceImpl;
import com.kb.erp.util.MessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("pcbaOut")
@Slf4j
public class PCBOutController {


    @Resource
    private PCBOutService service;


    @Resource
    private MaterialService materialService;

    @Resource
    private DYYServiceImpl dyyServiceImpl;

    //查询工单列表
    @PostMapping("/query")
    public BaseResult query(@RequestBody QueryTO to) throws JsonProcessingException {
        if (StringUtils.isBlank(to.getWorkOrderNumber2()) && StringUtils.isBlank(to.getWorkOrderNumber3()) && StringUtils.isBlank(to.getWorkOrderNumber()))
            return new BaseResult(new ArrayList<>());

        return new BaseResult(service.query(to));
    }


    @PostMapping("getWorkShop")
    public BaseResult getWorkShop() {


        return new BaseResult(service.getWorkShop());

    }


    @PostMapping("test")
    public void test() {


        materialService.test();

    }


    //根据工单，查询物料列表

    /**
     * 根据板材类型和材料类型查询物料清单
     *
     * @param plate 板材类型（PLATE），可能为空
     * @param type  材料类型，可能为空
     * @return BaseResult对象，包含查询到的物料清单或空列表
     */
    @PostMapping("/queryBomList")
    public BaseResult queryBomList(@RequestParam String plate,
                                   @RequestParam String type) {
        // 如果板材类型和材料类型都为空，则返回一个空的物料清单
        if (StringUtils.isBlank(plate) && StringUtils.isBlank(type))
            return new BaseResult(new ArrayList<>());

        // 调用服务层方法查询物料清单
        List<Material> materials = service.queryBomList(plate, type);
        // 如果查询到的物料清单不为空，则返回包含物料清单的BaseResult对象
        if (materials != null && materials.size() > 0) {
            return new BaseResult(materials);
        }

        // 如果查询结果为空，则返回一个空的物料清单
        return new BaseResult(new ArrayList<>());
    }


    @PostMapping("/add")
    public BaseResult add(@RequestBody AddTo to) throws Exception {


        if (to.getNos() != null)
            to.setCalculateList(to.getNos());

        return materialService.add(to);
    }


    @PostMapping("/get")
    public BaseResult get(@RequestBody Map<String, Long> params) throws Exception {
        Long id = params.get("id");
        return new BaseResult(materialService.get(id));
    }


    @PostMapping("/calculateBoard")
    public BaseResult calculateBoard(@RequestBody Map<String, Long> params) throws Exception {
        Long id = params.get("id");
        return new BaseResult(materialService.get(id));
    }


    //系统推荐
    @PostMapping("/recomend")
    public BaseResult recomend(@RequestBody Map<String, Object> params) throws Exception {


        Boolean isdetail = true;

        if (params.containsKey("isdetail")) {

            isdetail = (Boolean) params.get("isdetail");
        }

        if (params.containsKey("no")) {

            String no = (String) params.get("no");
            if (StringUtils.isNotBlank(no)) {
                return new BaseResult(materialService.recomend(no, isdetail));
            }
        } else if (params.containsKey("id")) {
            Object idObj = params.get("id");
            if (idObj != null) {
                Long id = ((Number) idObj).longValue();
                return new BaseResult(materialService.recomend(id, isdetail));
            }
        }

        return new BaseResult(null);


    }


    @PostMapping("/getIssuanceDetail")
    public BaseResult getIssuanceDetail(@RequestBody Map<String, String> params) throws Exception {

        String id = params.get("id");
        return new BaseResult(materialService.getIssuanceDetail(id));

    }

    @PostMapping("test1")
    public void test1() throws Exception {

        String id = "work7d9b9ace85d5492d893f8e46f8b01e66";
//        materialService.toHandle("1903999647603417090");

//        materialService.handle(id,"{\"code\":\"0\",\"desc\":\"成功\",\"data\":{\"details\":[{\"approvers\":\"\",\"approversMap\":null,\"auditSerial\":[],\"auditStatusStr\":\"\",\"closePerson\":\"911dd58ba1d53049e24e203942fc6cc4\",\"closePersonName\":\"\",\"closeReason\":\"同意。\",\"closeTime\":\"2025-03-13 14:05:48\",\"commentNum\":0,\"comments\":[],\"content\":\"\",\"createaTime\":\"2025-03-13 14:05:16\",\"creator\":\"911dd58ba1d53049e24e203942fc6cc4\",\"currentNode\":\"\",\"currentNodeId\":\"\",\"data\":{\"fo88286033e7074daf80f271f644e14f4c\":\"辅料\",\"fo8702d7c972ac44408d73c04710033e74\":\"FL202503130217\",\"fo8d4fc62278b048ea90cd78bfcb591b86\":[{\"childIndex\":1,\"fo0fc71450ee3249e3b720cabb2721c48d\":\" \",\"fo6c5a8f36f10647ea83963640ea693ff4\":\"2\",\"fo3580bfbb10f84a8588444f487aef623d\":\"S1170GB 2313 55% 0.1MM 18\\\"*24\\\"\",\"focb42ab50868a4a7e898162565dac6776\":\"张\"}]},\"definitionId\":\"defn727d745b2cd84bc9913ba0f9aaab853f\",\"departmentName\":\"金百泽电子->数字化中心（造物云）->数字工程部->数字技术\",\"deptFullName\":\"\",\"flowDetail\":null,\"formId\":\"\",\"formName\":\"\",\"formTitle\":\"辅料发放申请 \",\"headPic\":\"https://wework.qpic.cn/wwpic3az/335315_1lqUoke7TJqu5qw_1718092026/0\",\"id\":\"work7d9b9ace85d5492d893f8e46f8b01e66\",\"instanceTitle\":\"辅料发放申请\",\"isAlreadyAdd\":1,\"isAnonymous\":0,\"isClose\":1,\"isFree\":\"\",\"isTask\":\"\",\"isover\":\"1\",\"openId\":\"\",\"orderVersion\":4,\"orgId\":\"2d0e5316-4d19-49d7-b74c-136214e893d7\",\"personName\":\"陈泓成\",\"status\":1,\"title\":\"\",\"versions\":0,\"wxNickname\":\"\",\"wxUserId\":\"25313\"}]}}");


    }


    //发料申请
    @PostMapping("/issuance")
    public BaseResult issuance(@RequestBody AddTo to) throws Exception {

        materialService.issuance(to);
        return new BaseResult();
    }

    //辅料确认发货
    @PostMapping("/toHandle")
    public BaseResult toHandle(@RequestBody Issuance issuance) throws Exception {


        materialService.toHandle(issuance.getId(), issuance.getPerson());

        return new BaseResult();
    }


    @PostMapping("/recall")
    public BaseResult recall(@RequestBody String jsonString) throws Exception {
        LocalDateTime currentTime = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化当前时间
        String formattedTime = currentTime.format(formatter);

        // 输出日志
        log.info("流程中心回调当前时间: {}", formattedTime);

        log.info("流程中心回调表单json:" + jsonString);

        // 这里你可以对 jsonString 进行解析，或者直接返回 BaseResult
        // 比如：将 jsonString 转换成对象进行处理
        System.out.println("Received JSON String: " + jsonString);


        // 使用 Hutool 的 JSONUtil 将字符串转换为 JSONObject
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);

        // 获取 "data" 对象中的 "details" 数组
        JSONObject data = jsonObject.getJSONObject("data");

        // 显式指定类型为 JSONArray
        JSONArray details = data.getJSONArray("details");

        // 提取第一个元素中的 "id" 字段
        String id = details.getJSONObject(0).getStr("id");


        materialService.handle(id, jsonString);


        return new BaseResult(); // 你可以根据需求修改返回结果
    }

    public static void main(String[] args) {
        String dest = "example.pdf";
        try {
            createPdf(dest);
            System.out.println("PDF Created");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static void createPdf(String dest) throws Exception {
        // 1. 创建PDF写入对象
        PdfWriter pdfWriter = new PdfWriter(dest);

        // 2. 创建PDF文档对象
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);

        // 3. 创建内容文档对象
        Document document = new Document(pdfDocument);

        // 设置字体，解决中文显示问题
        PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", true);

        // 4. 添加标题
        document.add(new Paragraph("生产领料单")
                .setFont(font)
                .setBold()
                .setFontSize(16)
                .setTextAlignment(TextAlignment.CENTER));

        // 5. 添加日期、领料单号和领料部门
        Paragraph headingInfo = new Paragraph("2024年12月31日    领料单号: 128LL202412106888    领料部门: 制造部 - 化金")
                .setFont(font)
                .setTextAlignment(TextAlignment.LEFT)
                .setFontSize(12);
        document.add(headingInfo);

        // 6. 添加物料类别
        Paragraph materialCategory = new Paragraph("物料类别：化学品")
                .setFont(font)
                .setTextAlignment(TextAlignment.LEFT)
                .setFontSize(12);
        document.add(materialCategory);

        // 7. 添加空行
        document.add(new Paragraph("\n"));

        // 8. 表格列宽度
        float[] columnWidths = {1, 3, 2, 2, 2, 2, 3}; // 增加了备注列
        Table table = new Table(columnWidths);
        table.setWidthPercent(100);

        // 9. 表头
        table.addHeaderCell(new Cell().add(new Paragraph("物料编码").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("物料名称").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("规格").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("单位").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("现场库存").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("申请数量").setFont(font)));
        table.addHeaderCell(new Cell().add(new Paragraph("备注").setFont(font))); // 新增“备注”列

        // 10. 表格内容
        table.addCell(new Cell().add(new Paragraph("A8010003").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("酸性清洗剂 SE-250 20L/桶").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("升").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("80.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("60.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font))); // 备注列为空

        table.addCell(new Cell().add(new Paragraph("A8010003").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("酸性清洗剂 SE-250 20L/桶").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("升").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("80.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("20.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font))); // 备注列为空

        table.addCell(new Cell().add(new Paragraph("A8010001").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("过硫酸钠99% 工业级 25KG/包").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("千克").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("75.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("75.000").setFont(font)));
        table.addCell(new Cell().add(new Paragraph("").setFont(font))); // 备注列为空

        // 11. 输出表格
        document.add(table);

        // 12. 添加空行
        document.add(new Paragraph("\n"));

        // 13. 底部区域
        Paragraph footerInfo = new Paragraph("制单：张伟     物料审批：______     发料：______     接收：______")
                .setFont(font)
                .setTextAlignment(TextAlignment.LEFT)
                .setFontSize(12);
        document.add(footerInfo);

        // 获取页面宽度
        float pageWidth = pdfDocument.getDefaultPageSize().getWidth();

        // 14. 添加右下角用户信息
        Paragraph userInfo = new Paragraph("用户：李四") // 此处可以根据需求动态生成
                .setFont(font)
                .setTextAlignment(TextAlignment.RIGHT)
                .setFixedPosition(pageWidth - 150, 30, 100); // 调整宽度和位置
        document.add(userInfo);

        // 15. 获取当前时间并格式化
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Paragraph timeInfo = new Paragraph(currentTime)
                .setFont(font)
                .setTextAlignment(TextAlignment.RIGHT)
                .setFixedPosition(pageWidth - 150, 15, 100); // 调整宽度和位置
        document.add(timeInfo);

        // 16. 关闭文档
        document.close();


    }


    @PostMapping("/delete")
    public void deleteAll() {


        materialService.deleteAll();


    }


    @PostMapping("diyExport")
    public ResponseEntity<byte[]> diyExport(@RequestBody ExportTO to) throws IOException {


        List<DiyExportTO> tos = to.getTos();

        // 1. 合并相同的k3_name，并累加k3_number
        Map<String, Integer> mergedData = new HashMap<>();

        if (tos == null) {
            return null;
        }

        for (DiyExportTO tem : tos) {
            if (tem.getK3_number() != null) {
                mergedData.merge(tem.getK3_name(), tem.getK3_number(), Integer::sum);
            }
        }

        // 2. 将合并后的数据转化为 DiyExportTO 对象列表
        List<DiyExportTO> result = mergedData.entrySet().stream()
                .map(entry -> new DiyExportTO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

        // 3. 使用 EasyExcel 导出到 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, DiyExportTO.class)
                .sheet("Sheet1")
                .doWrite(result);

        EasyExcel.write("k3data", ExportTO.class).excelType(ExcelTypeEnum.XLSX).charset(Charset.forName("GBK")).sheet("k3").doWrite(result);

        // 4. 返回文件内容
        byte[] excelBytes = outputStream.toByteArray();

// Get current date in the desired format
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String currentDate = dateFormat.format(new Date());

// Create filename with "金蝶数据" + current date
        String filename = "k3data" + currentDate + ".xlsx";


// Set HTTP headers
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=" + filename);
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(excelBytes);
    }


    //提醒补充
    @PostMapping("/supple")
    public void supple(@RequestBody SuppleTO to) {

        String content = to.getPerson() + "需要物料补充，物料编码:" + to.getNo() + ",物料名称:" + to.getName() + ",目前库存:" + to.getStock();
//        MessageUtil.sentMessage("25313", content, "物料补充通知");
        MessageUtil.sentMessage("00273", content, "物料补充通知");
        MessageUtil.sentMessage("21064", content, "物料补充通知");

    }


    //每月一号执行
    @Scheduled(cron = "0 0 1 * * ?")
    @PostMapping("/mounthusecal")

    public void mounthusecal() {
        service.mounthusecal();
    }

    @PostMapping("/uploadWorkshop")
    public BaseResult uploadWorkshop(@RequestBody ExcelTO to) {

        materialService.uploadWorkshop(to);

        return new BaseResult();


    }


    @PostMapping("/easyExcel")
    public void exportEasyExcel(HttpServletResponse response,
                                @RequestBody BusinessQueryParam param) throws IOException {
        materialService.exportEasyExcel(response, param.getInputNo(), param.getK3Name(), param.getStartTime(), param.getEndTime());
    }


}
